<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
<head>
<title>Custom widget in Qt4</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Qt4, graphics, C++, 2D vector library, Custom widget in Qt4">
<meta name="description" content="In this part of the Qt4 tutorial, 
we create a custom widget.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-5536206-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

</head>

<body>

<div class="container2">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content2">


<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Custom widget in Qt4</h1>


<p>
In this part of the Qt4 C++ programming tutorial, we will create a custom widget.
</p>

<div class="big_hor">
<script type="text/javascript"><!--
google_ad_client = "ca-pub-9706709751191532";
/* big_horizontal */
google_ad_slot = "2904953388";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<p>
Most toolkits usually provide only the most common widgets like buttons, text widgets, 
sliders etc. No toolkit can provide all possible widgets. Programmers must create such 
widgets by themselves. They do it by using the drawing tools provided by the toolkit. 
There are two possibilities. A programmer can modify or enhance an existing widget. 
Or he can create a custom widget from scratch.
</p>

<h2>The Burning widget</h2>

<p>
In the next example we will create a custom burning widget. This widget can be 
seen in applications like Nero or K3B. The widget will be created from scratch. 
</p>

<div class="codehead">burning.h</div>
<pre class="code">
#pragma once

#include &lt;QWidget&gt;
#include &lt;QSlider&gt;
#include &lt;QFrame&gt;
#include "widget.h"

class Burning : public QFrame
{
  Q_OBJECT  

  public:
    Burning(QWidget *parent = 0);
    int getCurrentWidth();
    
  public slots:
    void valueChanged(int);
    
  private:
    QSlider *slider;
    Widget *widget;
    int cur_width;
    
    void initUI();
};
</pre>

<p>
This is the header file of the main window of the example.
</p>

<pre class="explanation">
public:
  Burning(QWidget *parent = 0);
  int getCurrentWidth();
</pre>

<p>
The getCurrentWidth() method is going to be used to determine the 
slider value. 
</p>

<pre class="explanation">
private:
  QSlider *slider;
  Widget *widget;
  int cur_width;
    
  void initUI();
</pre>

<p>
We will have two widgets on the client area of the window. A predefined slider 
and a custom widget. The <i>cur_width</i> variable will hold 
the current value from the slider. This value is used when painting the custom widget. 
</p>

<div class="codehead">burning.cpp</div>
<pre class="code">
#include &lt;QtGui&gt;
#include "burning.h"

Burning::Burning(QWidget *parent)
    : QFrame(parent)
{   
  initUI();
}

void Burning::initUI()
{
  const int MAX_VALUE = 750; 
  cur_width = 0; 
  
  slider = new QSlider(Qt::Horizontal , this); 
  slider->setMaximum(MAX_VALUE);
  slider->setGeometry(50, 50, 130, 30);

  connect(slider, SIGNAL(valueChanged(int)), 
          this, SLOT(valueChanged(int)));
  
  QVBoxLayout *vbox = new QVBoxLayout(this);
  QHBoxLayout *hbox = new QHBoxLayout();

  vbox->addStretch(1);

  widget = new Widget(this);  
  hbox->addWidget(widget, 0);

  vbox->addLayout(hbox);

  setLayout(vbox);    
}

void Burning::valueChanged(int val) 
{
  cur_width = val;
  widget->repaint();
}

int Burning::getCurrentWidth() 
{
  return cur_width;
}
</pre>

<p>
Here we build the main window of the example.
</p>

<pre class="explanation">
connect(slider, SIGNAL(valueChanged(int)), 
        this, SLOT(valueChanged(int)));
</pre>

<p>
When we move the slider, the valueChanged() slot is 
executed. 
</p>

<pre class="explanation">
void Burning::valueChanged(int val) 
{
  cur_width = val;
  widget->repaint();
}
</pre>

<p>
When we change the value of the slider, we store the new 
value and repaint the custom widget. 
</p>

<div class="codehead">widget.h</div>
<pre class="code">
#pragma once

#include &lt;QFrame&gt;

class Burning;

class Widget : public QFrame
{
  Q_OBJECT  

  public:
    Widget(QWidget *parent = 0);

  protected:
    void paintEvent(QPaintEvent *e);
    void drawWidget(QPainter &amp;qp);

  private:
    QWidget *m_parent;
    Burning *burn;
};
</pre>

<p>
This is the header file of the custom burning widget.
</p>

<pre class="explanation">
private:
  QWidget *m_parent;
  Burning *burn;
</pre>

<p>
We store a pointer to the parent widget. We get the 
<i>cur_width</i> through this pointer.
</p>

<div class="codehead">widget.cpp</div>
<pre class="code">
#include &lt;QtGui&gt;

#include "widget.h"
#include "burning.h"

const int PANEL_HEIGHT = 30;

Widget::Widget(QWidget *parent)
    : QFrame(parent)
{
  m_parent = parent;
  setMinimumHeight(PANEL_HEIGHT);
}

void Widget::paintEvent(QPaintEvent *e)
{       
  QPainter qp(this);
  drawWidget(qp);
  
  QFrame::paintEvent(e);  
}

void Widget::drawWidget(QPainter &amp;qp)
{  
  const int DISTANCE = 19;
  const int LINE_WIDTH = 5;
  const int DIVISIONS = 10;
  const float FULL_CAPACITY = 700;
  const float MAX_CAPACITY = 750;    
  
  QString num[] = { "75", "150", "225", "300", "375", "450", 
    "525", "600", "675" };
  int asize = sizeof(num)/sizeof(num[1]); 
  
  QColor redColor(255, 175, 175);
  QColor yellowColor(255, 255, 184);  
  
  int width = size().width();

  Burning *burn = (Burning *) m_parent;
  int cur_width = burn->getCurrentWidth();

  int step = (int) qRound(width / DIVISIONS);
  int till = (int) ((width / MAX_CAPACITY) * cur_width);
  int full = (int) ((width / MAX_CAPACITY) * FULL_CAPACITY);

  if (cur_width >= FULL_CAPACITY) 
  {
    qp.setPen(yellowColor); 
    qp.setBrush(yellowColor);
    qp.drawRect(0, 0, full, 30);
    qp.setPen(redColor);
    qp.setBrush(redColor);
    qp.drawRect(full, 0, till-full, PANEL_HEIGHT);

  } else if (till > 0)
  { 
    qp.setPen(yellowColor);
    qp.setBrush(yellowColor);
    qp.drawRect(0, 0, till, PANEL_HEIGHT);
  }

  QColor grayColor(90, 80, 60);
  qp.setPen(grayColor);
  
  for (int i=1; i &lt;=asize; i++) 
  {
    qp.drawLine(i*step, 0, i*step, LINE_WIDTH);
    QFont newFont = font();
    newFont.setPointSize(7);
    setFont(newFont);

    QFontMetrics metrics(font());

    int w = metrics.width(num[i-1]);
    qp.drawText(i*step-w/2, DISTANCE, num[i-1]);
  }
}
</pre>

<p>
Here we paint the custom widget. We paint the rectangle, vertical lines and the numbers. 
</p>

<pre class="explanation">
void Widget::paintEvent(QPaintEvent *e)
{       
  QPainter qp(this);
  drawWidget(qp);
  
  QFrame::paintEvent(e);  
}
</pre>

<p>
The drawing of the custom widget is delegated to the drawWidget() method.
</p>

<pre class="explanation">
const int DISTANCE = 19;
const int LINE_WIDTH = 5;
const int DIVISIONS = 10;
const float FULL_CAPACITY = 700;
const float MAX_CAPACITY = 750;   
</pre>

<p>
These are important constants. The DISTANCE is the distance of the numbers on the scale from 
the top of their parent border. The LINE_WIDTH is the vertical line width. The DIVISIONS is 
the number of parts of the scale. The FULL_CAPACITY is the capacity of the media. After it is 
reached, overburning happens. This is visualized by a red colour. The MAX_CAPACITY is the 
maximum capacity of a medium.
</p>

<pre class="explanation">
QString num[] = { "75", "150", "225", "300", "375", "450", 
  "525", "600", "675" }; 
</pre>

<p>
We use these numbers to build the scale of the Burning widget.
</p>

<pre class="explanation">
int width = size().width(); 
</pre>

<p>
We get the width of the widget. The width of the custom widget is dynamic. 
It can be resized by a user.
</p>

<pre class="explanation">
Burning *burn = (Burning *) m_parent;
int cur_width = burn->getCurrentWidth();
</pre>

<p>
We get the <i>cur_width</i> value.
</p>

<pre class="explanation">
int till = (int) ((width / MAX_CAPACITY) * cur_width);
int full = (int) ((width / MAX_CAPACITY) * FULL_CAPACITY); 
</pre>

<p>
We use the width variable to do the transformations. Between the values of the scale and the 
custom widget's measures. <!--Note that we use floating point values. We get greater precision in drawing.-->
</p>

<pre class="explanation">
qp.setPen(redColor);
qp.setBrush(redColor);
qp.drawRect(full, 0, till-full, PANEL_HEIGHT); 
</pre>

<p>
These three lines draw the red rectangle, indicating the overburning.
</p>

<pre class="explanation">
qp.drawLine(i*step, 0, i*step, LINE_WIDTH); 
</pre>

<p>
Here we draw the small vertical lines.
</p>

<pre class="explanation">
QFontMetrics metrics(font());

int w = metrics.width(num[i-1]);
qp.drawText(i*step-w/2, DISTANCE, num[i-1]);
</pre>

<p>
Here we draw the numbers of the scale. To precisely position the numbers, 
we must get the width of the string.
</p>


<div class="codehead">main.cpp</div>
<pre class="code">
#include &lt;QApplication&gt;
#include "burning.h"

int main(int argc, char *argv[])
{
  QApplication app(argc, argv);
  Burning window;

  window.resize(370, 200);
  window.move(300, 300);
  window.setWindowTitle("The Burning widget");
  window.show();

  return app.exec();
}
</pre>


<p>
This is the main file. 
</p>


<img src="/img/gui/qt4/burning.png" alt="The Burning widget">
<div class="figure">Figure: The Burning widget</div>


<p>
In this part of the Qt4 tutorial, we have created a custom Burning widget.
</p>


<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div>
<br>

<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified October 26, 2012  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>
